//
//  ModelViewController.swift
//  viewcontroller_test
//
//  Created by 潘茹燕 on 16/3/15.
//  Copyright © 2016年 海南开工信息技术有限公司. All rights reserved.
//

import UIKit

class ModelViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var producImageView: UIImageView!
    
    @IBOutlet weak var amountTextField: UITextField!
    
    // 容器的高度约束
    @IBOutlet weak var heightContraint: NSLayoutConstraint!
    
    @IBOutlet weak var imageViewHeightContraint: NSLayoutConstraint!
    
    @IBOutlet weak var amountInputViewContainer: UIView!
    @IBOutlet weak var backgroundView: UIView!
    
    @IBOutlet weak var buttonSubtract: UIButton!
    @IBOutlet weak var buttonPlus: UIButton!
    
    
    var repeatTimer: NSTimer?
    
    @IBAction func onClickSubtract(sender: AnyObject) {
        
        let v = Int(amountTextField.text!)
        
        if v > 1 {
            amountTextField.text = String(v! - 1)
        }
        
    }
    
    
    @IBAction func onButtonTouchDown(sender: AnyObject) {
        
        
        if sender === buttonSubtract || sender === buttonPlus {
            
            if repeatTimer != nil {
                repeatTimer?.invalidate()
                repeatTimer = nil
            }
            
            repeatTimer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: #selector(ModelViewController.repeatStart(_:)), userInfo: sender, repeats: true)
        }
        
    }
    
    // TouchUpInside 和 TouchUpOutside 都会执行
    @IBAction func onButtonTouchUpInside(sender: AnyObject) {
        
        if repeatTimer != nil {
            repeatTimer?.invalidate()
            repeatTimer = nil
        }
        
        
        changeAmount(sender as! UIButton)
        
        
    }
    
    
    func repeatStart(timer: NSTimer) {
        
        changeAmount(timer.userInfo as! UIButton)
        
    }
    
    func changeAmount(button: UIButton) {
        
        if button === buttonPlus {
            
            let v = Int(amountTextField.text!)
            amountTextField.text = String(v! + 1)
            
        }
        else if button === buttonSubtract {
            
            let v = Int(amountTextField.text!)
            
            if v > 1 {
                amountTextField.text = String(v! - 1)
            }
            
        }
    }
    
    
    
    
    
    
    @IBAction func onClickClose(sender: AnyObject) {
        
        dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    @IBAction func onClickChangeHeight(sender: AnyObject) {
        
        
        if heightContraint.constant != 200 {
            heightContraint.constant = 200
            imageViewHeightContraint.constant = 80
        }
        else
        {
            heightContraint.constant = 320
            imageViewHeightContraint.constant = 120
        }
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.backgroundView.layoutIfNeeded()
        }
        
        
        
        
    }
    
    // 保存容器的高度，在需要的时候恢复原样
    var originHeight: CGFloat = 0.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        producImageView.layer.borderWidth = 1.0
        producImageView.layer.borderColor = UIColor.groupTableViewBackgroundColor().CGColor
        producImageView.layer.masksToBounds = true
        producImageView.layer.cornerRadius = 4.0
        
        
        //backgroundView.layer.borderColor = UIColor.blackColor().CGColor
        //backgroundView.layer.borderWidth = 3.0
        
        
        backgroundView.layer.shadowColor = UIColor.blackColor().CGColor
        backgroundView.layer.shadowOpacity = 0.9
        backgroundView.layer.shadowRadius = 10.0
        backgroundView.layer.shadowOffset = CGSize(width: 0, height: 3)
        
        
        originHeight = heightContraint.constant
        
        amountTextField.delegate = self
        
        
        // 为键盘添加一个自定义的视图，随着键盘弹出显示在其上方
        let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        
        let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
        let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(ModelViewController.dismissKeyboard(_:)))
        
        toolbar.setItems([spaceButton, doneButton], animated: true)
        
        let accessoryView = toolbar
        

        amountTextField.inputAccessoryView = accessoryView
        
        
    }
    
    func dismissKeyboard(sender: AnyObject){
        
        amountTextField.resignFirstResponder()
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    override func viewWillAppear(animated: Bool) {
        
        // 添加检测键盘弹出事件
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ModelViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ModelViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        
        // 取消监测键盘弹出事件
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    func keyboardWillShow(notification: NSNotification) {
        
        
        // 因为我们只有一个输入框，所以相应的要简单一点
        
        let superViewRect = amountInputViewContainer.superview?.frame
        let rect = amountInputViewContainer.frame
        
        
        // 获得键盘的高度
        let userInfo = notification.userInfo
        
        
        let nsvalue = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        
        let keyboardRect = nsvalue.CGRectValue()
        
        NSLog("keyboard frame:\(keyboardRect)")
        
        
        // 计算输入框容器的底边到父视图底边的距离
        let distance = (superViewRect?.height)! - rect.origin.y - rect.height
        
        
        if distance < keyboardRect.height {
           
            heightContraint.constant += (keyboardRect.height - distance)
            
            UIView.animateWithDuration(0.5, animations: { () -> Void in
                self.backgroundView.layoutIfNeeded()
            })
            
        }
        
        
        
        
    }
    
    func keyboardWillHide(notification: NSNotification) {
        
        if heightContraint.constant != originHeight {
            
            heightContraint.constant = originHeight
            
            UIView.animateWithDuration(0.5, animations: { () -> Void in
                self.backgroundView.layoutIfNeeded()
            })
            
        }
        
    }
    
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        
        
        
        // NSRange -> Range<String.index>
        // 有更加简便的做法，就是将 Swift 的 String 类型转为 NSString，然后利用NSString的stringByReplacingCharactersInRange，但那样做并不保险
        // 因为NSString utf-16的， Swift 的 String 的实现因为隐含了细节，那么其真正的编码是什么格式并不十分确定，目前或许也是 utf-16的，但这并没有
        // 明确的官方文档证实这点，或许将来它的内部实现会发生改变，所以...
        // 参考：http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index
        let start = textField.text?.startIndex.advancedBy(range.location)
        let end = start?.advancedBy(range.length)
        
        
        //let pre = (textField.text?.stringByReplacingCharactersInRange(Range<String.Index>(start: start!, end: end!), withString: string))
        let pre = (textField.text?.stringByReplacingCharactersInRange(start!..<end!, withString: string))
        NSLog("\(pre)")
        
        
        

            
        do {
            
            let regex = try! NSRegularExpression(pattern: "^\\d*$", options: NSRegularExpressionOptions.CaseInsensitive)
            
            // 首先确保所有的输入都是数字
            if (regex.matchesInString(pre!, options: [], range: NSMakeRange(0, (pre?.characters.count)!)).count == 0 ){
                return false
            }
            else {
                
                // 当空的时候，添加一个 0
                if pre == "" {
                    textField.text = "0"
                    return false
                }
                else {
                    
                    
                    if pre?.characters.count > 1 && pre?.substringToIndex((pre?.startIndex.advancedBy(1))!) == "0" {
                        
                        // 如果第一个字符为 “0”， 那么说明要修正，但或许会有多个 “0”，例如原来为 10004， 当输入光标在1和0中间时候，
                        // 用户点了向前删除，那么将会变成 0004，显然在数值上没有问题，但看上去却很奇怪。所以最简便的方法就是先转整型
                        // 然后再转回字符串
                        let v = Int(pre!)
                        
                        textField.text = String(v!)
                        return false
                    }
                    
                }
                
            }
        
        }
        
        
        
        return true
    }
    
    

}
